import requests
from datetime import datetime
from config.Peizhi import Kz

# 从配置文件中导入 Kz 类并实例化，用于获取配置参数
kz = Kz()
# 假设的 API URL，用于将故障信息推送到该 API，需根据实际情况修改
API_URL = "http://222.134.245.144:17000/weizhang/VioModel/"

# 定义一个函数，用于将故障信息推送到 REST API
def send_fault_to_api(fault_info):
    """推送故障信息到 REST API"""
    try:
        # 发送 POST 请求，将故障信息以 JSON 格式发送到指定的 API 地址
        response = requests.post(API_URL, json=fault_info)
        if response.status_code == 201:
            # 如果请求成功（状态码为 201），打印成功推送的信息
            print(f"故障推送成功：{fault_info['gu_zhang_miao_shu']}")
        else:
            # 如果请求失败，打印失败信息，包含状态码和响应内容
            print(f"推送失败，状态码：{response.status_code}，响应：{response.text}")
    except requests.exceptions.RequestException as e:
        # 如果请求过程中出现异常，打印异常信息
        print(f"网络请求失败：{str(e)}")

# 定义一个函数，用于检查阀门和气缸的状态
def check_valves_and_cylinders():
    # 模拟获取设备的原始数据
    data = {
        "id": 1,
        "liu_liang_ji": "27.3625",
        "wan_neng_ya_li": "27.74375",
        "guan_hui_ya_li": "3000",
        "chu_neng_qi_ya_li": "3000",
        "zuan_ji_qi_ya": "3000",
        "pang_tong": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "wan_neng": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "dian_beng_1": {
            "deng": True,
        },
        "dian_beng_2": {
            "deng": True,
        },
        "shang_ya_jing": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "ke_bian_zha_ban": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "shang_zu_liu": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "xia_ya_jing": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "jian_qie_zha_ban": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "xia_zu_liu": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "bei_yong_fa": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "shang_zha_ban": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "xia_zha_ban": {
            "hong_yali": True,
            "hong_deng": True,
            "lv_yali": True,
            "lv_deng": True
        },
        "jin_ji_dian_yuan": {
            "deng": True,
        },
        "div_tong_xin": {
            "deng": True,
        },
        "HPU_tong_xin": {
            "deng": True,
        },
        "bao_jing": {
            "deng": True,
        },
        "lei_ji_power_low": {
            "deng": True,
        },
        "ye_wei_low": {
            "deng": True,
        },
        "zuan_ji_qi_ya_low": {
            "deng": True,
        },
        "beng_ya_li_low": {
            "deng": True,
        },
        "updated": "2025-02-14T10:50:34.521938",
        "created": "2025-02-14T10:50:34.521938"
    }
    # 从数据中获取当前主流量计的流量值，并转换为浮点数类型
    current_flow = float(data.get("liu_liang_ji", 0))
    # 这里假设功能输出前的流量值是已知的，实际应用中需要根据实际情况获取
    previous_flow = kz.previous_flow  # 示例值
    # 计算当前流量与之前流量的差值的绝对值
    flow_difference = abs(current_flow - previous_flow)
    # 从配置文件中获取流量差值的阈值
    threshold = kz.threshold
    # 定义需要检查的压力字段列表
    pressure_keys = [
        "pang_tong", "wan_neng", "shang_ya_jing", "ke_bian_zha_ban",
        "shang_zu_liu", "xia_ya_jing", "jian_qie_zha_ban", "xia_zu_liu",
        "bei_yong_fa", "shang_zha_ban", "xia_zha_ban"
    ]
    # 用于存储满足红灯和绿灯压力值都为 True 的字段
    satisfied_keys = []
    # 用于存储不满足红灯和绿灯压力值都为 True 的字段
    unsatisfied_keys = []
    # 遍历每个需要检查的压力字段
    for key in pressure_keys:
        # 获取当前字段的子数据
        sub_data = data.get(key)
        if sub_data.get("hong_yali") and sub_data.get("lv_yali"):
            # 如果当前字段的红灯和绿灯压力值都为 True，将该字段添加到满足条件的列表中
            satisfied_keys.append(key)
        else:
            # 否则，将该字段添加到不满足条件的列表中
            unsatisfied_keys.append(key)
    # 判断流量差值是否小于阈值
    if flow_difference < threshold:
        # 构造包含满足条件字段的结果消息
        result_message = f"电磁阀损坏堵塞、驱动气缸卡阻：{', '.join(satisfied_keys)}"
        if unsatisfied_keys:
            # 如果有不满足条件的字段，将其添加到结果消息中
            result_message += f"；以下字段不满足压力条件：{', '.join(unsatisfied_keys)}"
        # 打印结果消息
        print(result_message)
        # 构造故障信息
        fault_info = {
            "gu_zhang_ming_cheng": "电磁阀或气缸故障",
            "she_bei_ming_cheng": "阀门和气缸系统",
            "she_bei_qu_yu": "设备区域（需根据实际修改）",
            "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
            "gu_zhang_lei_xing": "流量与压力异常",
            "shi_ji_zhi": flow_difference,
            "gao_jing_zhi": threshold,
            "gu_zhang_miao_shu": result_message,
            "chu_li_zhuang_tai": "未处理"
        }
        # 调用 send_fault_to_api 函数推送故障信息
        send_fault_to_api(fault_info)

# 程序入口，调用 check_valves_and_cylinders 函数进行阀门和气缸状态检查
if __name__ == "__main__":
    check_valves_and_cylinders()